use crate::AppState;
use actix_session::Session;
use actix_web::{get, post, web, Error, HttpResponse, Result, Scope }; 
use std::fs::File;
use std::collections::HashMap;
use serde_json::{Value, json};

// 该模块的路由定义在这，便于管理。
pub fn sys_router() -> Scope {
    web::scope("/admin/sys").service(hello1).service(hello2)
}

#[get("/{name}/test.bu")]
async fn hello1(name: web::Path<String>) -> Result<HttpResponse, Error> {
    log::info!("{} - {}", "haha 我是日志", name);

    let f = File::open("asdfasf.html")?;
    log::info!("{:?}", f);


    let mut hashmap:HashMap<String, Value> = HashMap::new();
    hashmap.insert(String::from("name"), json!("理解"));
    hashmap.insert(String::from("age"), json!(542));

    Ok(HttpResponse::Ok().json(hashmap)) 
}

#[get("/{name}/index.bu")]
async fn hello2(
    name: web::Path<String>,
    session: Session,
    data: web::Data<AppState>,
) -> Result<HttpResponse, Error> {
    log::info!("{} - 我的名字叫: {}", "haha 我是日志", name);
    log::info!("从AppState 中读取的数据:{}", data.app_name);

    if let Some(v) = session.get::<i32>("name_key")? {
        let counter = v + 1;
        log::info!("session 中有个数据：{}", v);
        session.insert("name_key", counter)?;
    } else {
        log::info!("session 中没有数据，我添加一个。");
        session.insert("name_key", 0)?;
    };

    Ok(HttpResponse::Ok().json(vec!["asdf", "2323", "2323fa"]))
}

pub async fn hello3( ) -> Result<HttpResponse> {  

    Ok(HttpResponse::Ok()
        .content_type("text/plain")
        .body(format!("Your name is {}", 34)))
}